const express = require('express')
const router = express.Router()
const gbookAction = require('../Controller/gbook')
const formatTime = require('../tool/formatTime')
const check = require('../mid')
const categoryAction = require('../Controller/categorys')




//渲染评论管理列表页面
router.get('/gbook-admin', function (req, res) {
    res.render('gbook-admin.html')
})

//渲染评论管理列表页面
router.get('/gbook', function (req, res) {
    let cate;
    categoryAction.all(function (doc) {
        cate = doc
        gbookAction.all().then(gbooks => {
            gbooks.forEach(item => {
                item.createAt = formatTime(item.createAt)
            })
            res.render('blog/gbook.html', { cate,gbooks })
        })

    })

})




//增加留言
router.post('/addgbook', function (req, res) {
    if (req.session.user) {
        req.body.name = req.session.user.name
        req.body.img = req.session.user.Avatar
    } else {
        req.body.img = '/public/static/images/tx' + Math.floor(Math.random() * (10 - 1 + 1) + 1) + '.jpg'
    }
    let comment = req.body
    gbookAction.setGbook(comment).then(function (doc) {
        res.redirect('/gbook')
    })
})

//获取留言
router.get('/getgbook', function (req, res) {
    gbookAction.all().then(doc => {
        doc.forEach(item => {
            item.createAt = formatTime(item.createAt)
        })
        res.json(doc)
    })
})



//删除评论
router.get('/deleteGbook', check.passCmts, function (req, res) {
    let dearr = req.query.arr
    gbookAction.deById(dearr, function (doc) {
        if (doc.ok == 1) {
            res.json({ code: 1, msg: '更新成功' })
        } else {
            res.json({ code: 0, msg: '更新失败' })
        }
    })

})



module.exports = router